<?php
class dbaseManager
{
    //TODO: replace these sample values with yours  
    const global_host = "mysql.fn-sandbox.net";
    const global_username = "izinin_sql";
    const global_password = "XXXXXXX"; // hidden from the code since it is in public domain
    const global_dbname = "izinin";

    function __construct(){
        if(!$this->bookstore_connect_dbase()){
            throw new Exception(mysql_error());
        }
    }
    
    function __destruct() {
        $this->bookstore_disconnect_dbase();
    }
    
    public function getProductList(){
        $db = self::global_dbname;
        $queryStr = "select p.productid from $db.product p";
        
        $result = mysql_query($queryStr);
		$productList = array();
        while($row = mysql_fetch_assoc($result)){
            $productList[] = $row['productid'];
        }
        
        mysql_free_result($result);
		
		if(count($productList) == 0){
			throw new Exception('empty product list');		
		}
		
		return $productList;
    }
   
    public function getTicket($var_account, $var_prodid){
        $db = self::global_dbname;

        $queryStr = "select t.ticket from $db.customer c ".
                    " inner join $db.customer_product t on c.id = t.customer_id ".
                        " inner join $db.product p on p.id = t.product_id ".
                            " where c.accountdigest = '$var_account' and p.productid = '$var_prodid'";
                            
        $result = mysql_query($queryStr);
        $ticket = "";
        if(mysql_num_rows($result) > 0){
            $row = mysql_fetch_assoc($result);
            $ticket = $row['ticket'];
        }

        mysql_free_result($result);
        return $ticket;
    }
    
    public function saveTicket($var_account, $var_ticket, $var_prodid){
        $db = self::global_dbname;
        $queryStr = "CALL $db.addTicket('$var_account', '$var_ticket', '$var_prodid')";

        mysql_query($queryStr);
    }
    
    public function getProductUrl($var_prodid){
        $db = self::global_dbname;

        $queryStr = "SELECT p.url FROM $db.product p WHERE p.productid = '$var_prodid' LIMIT 1";
                            
        $result = mysql_query($queryStr);
        $url = "not-found";
        if(mysql_num_rows($result) > 0){
            $row = mysql_fetch_assoc($result);
            $url = $row['url'];
        }

        mysql_free_result($result);
        return $url;
    }
   
    private function bookstore_connect_dbase(){	
        $result = mysql_connect(self::global_host, self::global_username, self::global_password);
        
        if($result){
            $result = mysql_select_db(self::global_dbname);
        }
        
        return $result;
        }

    private function bookstore_disconnect_dbase(){
        mysql_close();
        return true;
        }	
}
?>
